﻿using System;
using System.Collections.Generic;
using SMF.HowTo.Shared.Extensions;

namespace SMF.HowTo.Shared
{
    public class EasterEggUnlocker
    {
        private readonly Queue<int> _entries;
        private readonly int[] _key;

        public EasterEggUnlocker(int[] key)
        {
            _key = key;
            _entries = new Queue<int>(key.Length);
        }

        public event Action Unlocked;

        public void Enter(int entry)
        {
            _entries.Enqueue(entry);

            if (_entries.Count > _key.Length)
            {
                _entries.Dequeue();
            }

            if (Unlocked != null && KeySearch(_key, _entries.ToArray()))
            {
                _key.ForEach(i => _entries.Dequeue());
                Unlocked();
            }
        }

        private static bool KeySearch(int[] key, int[] entries)
        {
            for (int i = 0; i < entries.Length; i++)
            {
                int matches = 0;
                for (int j = 0; j < key.Length && i + j < entries.Length; j++)
                {
                    if (entries[i + j] == key[j])
                    {
                        matches++;
                    }
                    else
                    {
                        break;
                    }
                }

                if (matches == key.Length)
                {
                    return true;
                }
            }

            return false;
        }
    }
}